<template>
  <q-form ref="form" @submit="onSubmit" class="q-gutter-md q-pb-xl">
    <formInput ref='formInput' :fieldlist="formFields" />

    <div class="row justify-center">
      <img class="shadow-2" :src="qrcodeUrl" :width="imgPix.w" :height="imgPix.h" style="width:317px; height:368px " />
      <canvas id="qrcode" style="display: none;"></canvas>
    </div>

    <history v-if="mode === 'edit'" class="q-mb-xl" :data="historyData" :escape="historyEscape" :tableFields="tableFields" />

    <q-page-sticky position="bottom" :offset="[0, 28]">
      <q-btn label="保存" type="submit" color="primary" class="btn-fixed-width" icon="save" :loading="saving" />
      <q-btn label="查看店铺" @click="goShop" color="secondary" class="q-ml-md" v-if="mode === 'edit'" />
      <!-- <q-btn label="返回" @click="onReset" color="primary" outline class="q-ml-md bg-white" /> -->
    </q-page-sticky>
  </q-form>
</template>

<script>
import { defineComponent } from 'vue';
import formInput from 'src/components/FormInput.vue';
import { detailPageMix } from 'src/lib/mixin.js';
import history from 'src/components/history.vue'
import { useMeta, copyToClipboard } from 'quasar';
import { useStore } from 'stores/store';
import QRCode from 'qrcode';

export default defineComponent({
  name: 'shopDetail',
  setup (props, context) {
    const $store = useStore();
    const modelLabel = '店铺信息';
    const moduleName = 'shop';
    const detailApi = `/c2/tenant/${moduleName}/detail`; // 明细数据接口
    const createApi = `/c2/tenant/${moduleName}/create`; // 新建数据接口
    const updateApi = `/c2/tenant/${moduleName}/update`; // 更新数据接口

    useMeta({
      // 设置文件标题
      title: `${modelLabel}详情 - ${$store.siteConfig.appName} - 木多鱼系列`
    });

    return {
      modelLabel,
      moduleName,
      detailApi,
      createApi,
      updateApi
    }
  },
  components: {
    formInput,
    history
  },
  mixins: [detailPageMix],
  data () {
    return {
      formFields: {
        logo_img: { type: 'image', label: '店铺图片', value: [], readonly: false, limit: 1 },
        shop_name: { type: 'input', label: '店铺名称 *', value: '', rules: [val => !!val || '请输入店铺名称'], readonly: false },
        linkman: { type: 'input', label: '联系人', value: '', readonly: false },
        tel: { type: 'input', label: '联系电话', value: '', rules: [this.checkCode], readonly: false },
        short_tel: { type: 'input', label: '联系短号', value: '', readonly: false },
        address: { type: 'input', label: '店铺地址', value: '', readonly: false },
        intro: { type: 'input', label: '简介', value: '', textarea: true, readonly: false },
        state: { type: 'toggle', label: '状态', value: 1, trueValue: 1, trueLabel: '开张', falseValue: 0, falseLabel: '关闭', readonly: false },
        url: { type: 'input', label: '网店网址', value: '', autogrow: true, readonly: true }
      },

      qrcodeUrl: '/images/default_img.jpg',
      imgPix: { w: 950, h: 1100 }
    };
  },
  async created () {
  },
  mounted () {
    this.refreshData(() => {
      this.formFields.url.value = this.shopUrl;
      this.generateQR();
    });
  },
  methods: {
    setReadonly () {
      this.mode = this.data ? 'edit' : 'add';
      if (this.mode === 'edit') {
        this.id = this.data.id;
      }
    }, // 替换混合里的同名方法
    onSubmit () {
      this.$refs.formInput.validateAll();
      this.$nextTick(() => {
        this.$refs.form.validate().then(ot => {
          if (ot) {
            this.saving = true;
            this.$refs.formInput.getFormData().then(data => {
              this.saveData(data);
            }).catch(e => {
              console.log(e);
              this.saving = false
            });
          }
        });
      });
      // this.saving = true;
      // this.saveData();
    },
    goShop () {
      if (this.data && this.data.uuid) {
        const fullPath = this.shopUrl;

        const msg = `${this.data.shop_name}店铺地址：${fullPath}`;
        console.log(msg);
        copyToClipboard(msg);
        this.$q.notify({
          message: '店铺地址已经复制到系统剪贴板，请直接粘贴到微信中发送',
          color: 'info',
          icon: 'info',
          position: 'center',
          timeout: 4000
        });

        window.open(fullPath, '_blank');
      }
    },
    generateQR () {
      QRCode.toCanvas(this.shopUrl, { width: 950 }, (err, cvs) => {
        if (err) console.log(err);
        this.$nextTick(() => {
          const w = this.imgPix.w, h = this.imgPix.h;
          const canvas = document.getElementById('qrcode');
          const ctx = canvas.getContext('2d');
          const devicePixelRatio = window.devicePixelRatio || 1;
          const backingStoreRatio = ctx.webkitBackingStorePixelRatio || 1;
          const ratio = (devicePixelRatio / backingStoreRatio) * 2;
          canvas.width = w * ratio;
          canvas.height = h * ratio;
          canvas.style.width = w + 'px';
          canvas.style.height = h + 'px';
          ctx.scale(ratio, ratio);
          ctx.fillStyle = '#fff';
          ctx.fillRect(0, 0, w, h);
          ctx.drawImage(cvs, 0, 100); // qr位置

          ctx.fillStyle = '#000';
          ctx.textAlign = 'center';
          ctx.font = '68px 宋体';
          ctx.fillText(this.data.shop_name, w / 2, 80);

          ctx.font = '44px 宋体';
          ctx.fillText(`${this.data.linkman} ${this.data.tel}  ${this.data.short_tel}`, w / 2, 150);

          ctx.font = '60px 宋体';
          ctx.fillText('扫码下单 送货上门', w / 2, 1050);

          // 获取图像元素
          const logoSrc = this.data.logo_img.length > 0 ? this.data.logo_img[0].image : '/images/default_img.jpg';

          const logo = new Image();
          logo.src = logoSrc;
          logo.onload = () => {
            // 计算目标宽度和高度
            const targetWidth = 100;
            const targetHeight = 100;

            // 计算裁剪区域
            let cropX, cropY, cropWidth, cropHeight;
            if (logo.width > logo.height) {
              cropWidth = logo.height;
              cropHeight = logo.height;
              cropX = (logo.width - logo.height) / 2;
              cropY = 0;
            } else {
              cropWidth = logo.width;
              cropHeight = logo.width;
              cropX = 0;
              cropY = (logo.height - logo.width) / 2;
            }

            // 创建一个临时的 canvas 来绘制裁剪后的图像
            const tempCanvas = document.createElement('canvas');
            const tempCtx = tempCanvas.getContext('2d');
            tempCanvas.width = cropWidth;
            tempCanvas.height = cropHeight;

            // 绘制裁剪后的图像到临时 canvas
            tempCtx.drawImage(logo, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight);

            // 创建一个带有圆角的路径
            const cornerRadius = 20; // 圆角半径
            const centerX = (w - targetWidth) / 2;
            const centerY = (h - targetHeight) / 2;

            // 绘制白色边框
            ctx.beginPath();
            ctx.moveTo(centerX + cornerRadius, centerY);
            ctx.arcTo(centerX + targetWidth, centerY, centerX + targetWidth, centerY + targetHeight, cornerRadius);
            ctx.arcTo(centerX + targetWidth, centerY + targetHeight, centerX, centerY + targetHeight, cornerRadius);
            ctx.arcTo(centerX, centerY + targetHeight, centerX, centerY, cornerRadius);
            ctx.arcTo(centerX, centerY, centerX + targetWidth, centerY, cornerRadius);
            ctx.closePath();
            ctx.lineWidth = 8;
            ctx.strokeStyle = '#fff';
            ctx.stroke();

            // 绘制带有圆角的路径
            ctx.beginPath();
            ctx.moveTo(centerX + cornerRadius, centerY);
            ctx.arcTo(centerX + targetWidth, centerY, centerX + targetWidth, centerY + targetHeight, cornerRadius);
            ctx.arcTo(centerX + targetWidth, centerY + targetHeight, centerX, centerY + targetHeight, cornerRadius);
            ctx.arcTo(centerX, centerY + targetHeight, centerX, centerY, cornerRadius);
            ctx.arcTo(centerX, centerY, centerX + targetWidth, centerY, cornerRadius);
            ctx.closePath();
            ctx.clip();

            // 将临时 canvas 的内容绘制到主 canvas 上
            ctx.drawImage(tempCanvas, (w - targetWidth) / 2, (h - targetHeight) / 2, targetWidth, targetHeight);

            this.qrcodeUrl = canvas.toDataURL('image/png');
          };

          // this.qrcodeUrl = canvas.toDataURL('image/png');
        });
      });
    }
  },
  computed: {
    shopUrl () {
      const routeData = this.$router.resolve({
        path: `/shop/${this.data.uuid}/list`
      });
      const fullPath = window.location.origin + routeData.href;
      return fullPath;
    }
  },
  watch: {
  }
});
</script>
